package com.dl698.axdr;

import com.dl698.asn1.axdr.AxdrType;
import com.dl698.util.ReverseByteArrayInputStream;
import com.dl698.util.ReverseByteArrayOutputStream;

import java.io.IOException;

/**
 * ROAD类
 * 实现读取对象属性描述符的编解码
 * 
 * @author wind
 * @version 1.1.1
 */
public class ROAD implements AxdrType {

    private byte[] dataCode = null;
    private SubSeqOfOads oads = null;
    private OAD oad = null;

    /**
     * 默认构造函数
     */
    public ROAD() {
    }

    /**
     * 设置数据编码
     * 
     * @param dataCode 数据编码
     */
    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    /**
     * 设置ROAD参数
     * 
     * @param oad  对象属性描述符
     * @param oads 对象属性描述符序列
     */
    public void setAll(OAD oad, SubSeqOfOads oads) {
        this.oad = oad;
        this.oads = oads;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) {
        int codeLength = 0;

        oad = new OAD();
        codeLength += oad.decode(input);

        oads = new SubSeqOfOads();
        codeLength += oads.decode(input);

        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) {
        int codeLength;

        if (dataCode != null) {
            codeLength = dataCode.length;
            for (int i = dataCode.length - 1; i >= 0; i--) {
                try {
                    output.write(dataCode[i]);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        } else {
            if (oads != null && oad != null) {
                codeLength = 0;
                codeLength += oads.encode(output);
                codeLength += oad.encode(output);
            } else {
                throw new RuntimeException("oads || oad is null");
            }
        }

        return codeLength;
    }

    /**
     * 编码并保存
     * 
     * @param encodingSizeGuess 编码大小预估
     */
    public void encodeAndSave(int encodingSizeGuess) throws IOException {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    @Override
    public String toString() {
        if (oad != null && oads != null) {
            return "sequence: {" + "oad: " + oad + ", oads: " + oads + "}";
        } else {
            return "oads || oad is null";
        }
    }

    /**
     * 获取对象属性描述符序列
     * 
     * @return 对象属性描述符序列
     */
    public SubSeqOfOads getOads() {
        return oads;
    }

    /**
     * 获取对象属性描述符
     * 
     * @return 对象属性描述符
     */
    public OAD getOad() {
        return oad;
    }
}